/*
 * Author:  Copyright (c) 2013 Toby
 * E-Mail:  smurffit@gmail.com
 * Web:     https://code.google.com/p/chrome-mfi-filter4kiva/
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

/* ----- FUNC ----- */

/**
 * The result of getMfiName() to be returned to background.js
 * 
 * @param count
 *            {String} the name to identify the message
 * @param highlights
 *            {boolean} unused
 * @param filtered
 *            {String} the name of the MFI
 */
function result(count, highlights, filtered)
{
	this.count = count;
	this.highlights = highlights;
	this.filtered = filtered;
}

/* ----- END FUNC ----- */

var timer;
getMfiName();

/**
 * Checks the page every 100ms until the MFI name is found. The result is sent to background.js If
 * nothing is found it gives up after 10 seconds.
 */
function getMfiName()
{
	if (timer !== undefined)
	{
		console.warn('BUG: timer already defined!');
		return;
	}

	var partnerNode, timeout = (new Date().getTime()) + 10000;

	timer = setInterval(function()
	{
		if (new Date().getTime() > timeout)
		{
			console.error('Timeout reached, couldn\'t find MFI name.');
			clearInterval(timer);
			return;
		}

		partnerNode = document.getElementsByTagName('figcaption');
		if (partnerNode !== undefined) // && partnerNode.length > 0
		{
			var link;
			for ( var i = 0, len = partnerNode.length; i < len; i++)
			{
				link = partnerNode[i].innerHTML.match(/\/partners\/\d{1,4}/);

				if (link !== null)
				{
					chrome.extension.sendMessage(new result('mfiName', false, JSON
							.stringify(link[0].substring(10))));
					clearInterval(timer);
					return;
				}
			}
		}
	}, 100);
}
